

function Observer(){
  this.events={}
}
Observer.prototype.subscribe=function(key,fn){
  this.events[key]?this.events[key].push(fn):this.events[key]=[fn]
}
Observer.prototype.emit=function(key){
  this.events[key]&&this.events[key].forEach(fn=>fn())
}

const observer = new Observer()

observer.subscribe('resolves',function(){
  console.log(123);
})
observer.emit('resolves')

function MyPromise(fn) {
  this.value = undefined;
  const _this = this;
  this.observer = new Observer();
  function resolve(value) {
    _this.value = value;
    _this.observer.emit("resolve");
  }
  function reject(err) {
    
    console.log(err);
  }
  fn(resolve, reject);
}


MyPromise.prototype.then = function (fn) {
  return new MyPromise((resolve, reject) => {
    this.observer.subscribe("resolve", () => {
      resolve(fn(this.value));
    });
  });
};


const p = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve("成功");
  }, 1000);
});


p.then((res) => {
  console.log(res);
  return 123
}).then(res=>{
  console.log(res);
  return 456
}).then(res=>{
  console.log(res);
})